package com.app.couponsharelife.ui.main.me.profit.fragment

import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gavin.com.library.PowerfulStickyDecoration
import com.gavin.com.library.listener.PowerGroupListener
import com.makeramen.roundedimageview.RoundedImageView
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.EarningsRecord
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.UserEarningsBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.listener.MyMultiPurposeListener
import com.app.couponsharelife.ui.main.me.profit.record.ProfitRecordActivity
import com.app.couponsharelife.utils.AppUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.fragment_offline_profit.*
import kotlinx.android.synthetic.main.profit_list_rvtop.view.*
import kotlinx.android.synthetic.main.profit_record_item.view.*
import java.text.SimpleDateFormat
import java.util.*

/**
 *Created by xct on 2019/2/22
 *Description:线下收益列表页面
 */
class OfflineProfitFragment:LazyFragment() {
    private var pageIndex=1
    private var OfflineTime=""
    private var dataList= arrayListOf<EarningsRecord>()
    private var decoration:PowerfulStickyDecoration?=null
    private var adapter:MyAdapter?=null
    val simpleDateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
    companion object {
        fun newInstance(): OfflineProfitFragment {
            val fragment = OfflineProfitFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_offline_profit

    override fun initViews() {
        setRefresh()
        adapter=MyAdapter()
        offlineProfit_rv.layoutManager=LinearLayoutManager(activity)
        val listener=object : PowerGroupListener {
            override fun getGroupName(position: Int): String {
                return dataList[position].headTime
            }
            override fun getGroupView(position: Int): View {
                val view=LayoutInflater.from(activity).inflate(R.layout.profit_list_rvtop, null, false)
                view.profitList_tvTime.text=dataList[position].headTime
                view.profitList_tvPrice.text="结算收益 ¥"+dataList[position].totalMoney
                return view
            }
        }
        decoration= PowerfulStickyDecoration.Builder.init(listener).setGroupBackground(resources.getColor(R.color.gray_f3f4)).build()
        offlineProfit_rv.addItemDecoration(decoration!!)
        offlineProfit_rv.adapter=adapter
        offlineProfit_butTime.setOnClickListener {
            (activity as ProfitRecordActivity).timePickers()
        }
    }

    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        offlineProfit_smartrefresh.setOnMultiPurposeListener(object : MyMultiPurposeListener {
            override fun headerReleased() {
                animationDrawable.start()
            }

            override fun headerMoving(percent: Float) {
                setAnima(percent)
            }

            override fun headerFinish() {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }

            override fun loadMore() {
                getData(false)
            }

            override fun refresh() {
                pageIndex=1
                getData(true)
            }
        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    private fun getData(isRefresh:Boolean){
        if (pageIndex==1){
            showProgressDialog("加载中...")
        }
        val map= HashMap<String,String>()
        map["pageNo"]=pageIndex.toString()
        map["pageSize"]="10"
        map["userId"]=AppUtils.getString(Contacts.USERID, "")
        map["type"]="2"
        map["time"]=OfflineTime
        RetrofitWorker.retrofitWorker.getAlreadyEarnings(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<UserEarningsBean>>(){
                    override fun onComplete() {

                    }
                    override fun onNext(it: RemoteResultBean<UserEarningsBean>) {
                        if (pageIndex==1){
                            dismissProgressDialog()
                            dataList.clear()
                        }
                        if (it.code==200){
                            if (it.data!!.records.isNotEmpty()){
                                if (pageIndex==1){
                                    offlineProfit_llnodata.visibility= View.GONE
                                    offlineProfit_rv.visibility= View.VISIBLE
                                    if (isRefresh){
                                        offlineProfit_smartrefresh.finishRefresh()
                                    }
                                }else{
                                    offlineProfit_smartrefresh.finishLoadMore()
                                }
                                setData(it.data!!.records!!)
                                /*if (it.data!!.records!!.size<10){
                                    offlineProfit_smartrefresh.finishLoadMoreWithNoMoreData()
                                }*/
                                pageIndex++
                                adapter!!.notifyDataSetChanged()
                                decoration!!.clearCache()
                            }else{
                                if (pageIndex==1&&dataList.size==0){
                                    offlineProfit_smartrefresh.finishRefresh()
                                    offlineProfit_llnodata.visibility= View.VISIBLE
                                    offlineProfit_errormsg.text="您还没有收益记录哦"
                                    offlineProfit_butTime.visibility=View.GONE
                                    offlineProfit_rv.visibility= View.GONE
                                }else{
                                    showToastMsg("没有更多数据了！")
                                }
                                offlineProfit_smartrefresh.finishLoadMoreWithNoMoreData()
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (pageIndex==1){
                            dismissProgressDialog()
                            if (isRefresh){
                                offlineProfit_smartrefresh.finishRefresh()
                                offlineProfit_smartrefresh.finishLoadMoreWithNoMoreData()
                            }
                        }
                        if (e is OtherException){
                            //showToastMsg("没有找到任何数据，换一个试试！")
                            offlineProfit_llnodata.visibility= View.VISIBLE
                            offlineProfit_errormsg.text="没有找到${OfflineTime}的收益记录"
                            offlineProfit_butTime.visibility=View.VISIBLE
                            offlineProfit_rv.visibility= View.GONE
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    override fun lazyLoad() {
        getData(false)
    }
    private fun setData(list:List<EarningsRecord>){
        val time=simpleDateFormat.format(System.currentTimeMillis())
        for (i in 0 until list.size){
            val datas=list[i]
            val times=datas.createTime.substring(0,7)
            datas.headTime=if (times==time){"本月"}else {times}
            dataList.add(datas)
        }
    }
    fun refreshData(times:String){
        OfflineTime=times
        pageIndex=1
        getData(true)
    }
    private inner class MyAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.profit_record_item, parent, false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return dataList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (dataList.size>0){
                if (holder is MyHolder){
                    val datas=dataList[position]
                    holder.tvName!!.text=datas.nickName
                    var type=""
                    var id=0
                    if ("4"==datas.type){
                        type="分红奖励"
                    }else {
                        type = if (1 == datas.moneytype) {
                            "直推"
                        } else if(2 == datas.moneytype){
                            "间推"
                        }else{
                            ""
                        }
                        var type1=""
                        when(datas.type){
                            "10"->{
                                type1="首席奖励"
                                id=R.drawable.shop_type_sj
                                holder.tvExplain!!.visibility=View.GONE
                            }
                            "11"->{
                                type1="合伙人奖励"
                                id=R.drawable.shop_type_sj
                                holder.tvExplain!!.visibility=View.GONE
                            }
                            "20"->{
                                type1="门店收银奖励"
                                id=R.drawable.shop_type_shop
                                holder.tvExplain!!.visibility=View.VISIBLE
                                holder.tvExplain!!.text="次月25日结算"
                            }
                        }
                        type += type1
                    }
                    holder.tvType!!.text=type
                    holder.faceImag!!.setImageResource(id)
                    holder.tvTime!!.text=datas.createTime
                    holder.tvPrice!!.text=datas.credit2
                }

            }
        }

    }
    private inner class MyHolder(itemview: View): RecyclerView.ViewHolder(itemview){
        var tvName: TextView?=null
        var tvType:TextView?=null
        var tvOrType:TextView?=null
        var tvTime:TextView?=null
        var faceImag: RoundedImageView?=null
        var tvJia:TextView?=null
        var tvPrice:TextView?=null
        var tvExplain:TextView?=null
        init {
            tvName=itemview.tvNikname
            tvType=itemview.onlin_tvType
            tvOrType=itemview.onlin_tvOrType
            tvTime=itemview.onlin_tvTime
            faceImag=itemview.userimag
            tvJia=itemview.onlin_tvJia
            tvPrice=itemview.tvProfitRecordMoney
            tvExplain=itemview.onlin_tvExplain
        }
    }
}